<template>
  <view class="cognition-container">
    <!-- 顶部胶囊导航栏 -->
    <CapsuleNav 
      :items="categories"
      :active-index="activeIndex"
      :allow-edit="true"
      @change="handleCategoryChange"
      @add-folder="handleAddCategory"
      @delete-folder="handleDeleteCategory"
    />

    <!-- 双列瀑布流式记录列表 -->
    <view class="waterfall-container" v-if="currentContents.length > 0">
      <view 
        v-for="item in currentContents" 
        :key="item.id"
        class="record-card"
        :class="{ 'pinned-card': item.isPinned }"
        @click="handleEditRecord(item)"
        @longpress="handleLongPress(item)"
      >
        <view class="card-header">
          <text class="record-title">
            {{ activeCategory === '人际' ? item.name : item.title || '未命名' }}
          </text>
          <uni-icons 
            v-if="item.isPinned"
            type="pin-filled"
            size="16"
            color="#F97D1C"
            class="pin-icon"
          ></uni-icons>
        </view>
        
        <!-- 人际卡片特殊字段 -->
        <template v-if="activeCategory === '人际'">
          <text class="record-desc" v-if="item.relation">
            {{ item.relation }}
          </text>
          <view class="birthday-reminder" v-if="item.birthday">
            <switch 
              :checked="item.reminderEnabled"
              @change="(e) => toggleReminder(item.id, e.detail.value)"
              color="#87CEEB"
              class="reminder-switch"
            />
            <text class="birthday-text">
              {{ formatBirthday(item.birthday) }}
              {{ item.reminderEnabled ? '(提醒开启)' : '(提醒关闭)' }}
            </text>
          </view>
        </template>
        
        <text class="record-time">
          {{ formatDate(item.updatedAt || item.createdAt) }}
        </text>
      </view>
    </view>

    <!-- 空状态提示 -->
    <view class="empty-tip" v-else>
      <uni-icons type="info" size="24" color="#999"></uni-icons>
      <text>暂无记录，点击下方按钮添加</text>
    </view>

    <!-- 右下角添加按钮 -->
    <ThemeButton 
      type="primary" 
      class="add-button"
      @click="handleAddRecord"
    >
      <uni-icons type="plus" size="24" color="white"></uni-icons>
    </ThemeButton>

    <!-- 操作菜单 -->
    <uni-popup ref="actionMenu" type="bottom" safe-area>
      <view class="action-menu">
        <view class="menu-item" @click="handleTogglePin">
          <uni-icons 
            :type="selectedRecord?.isPinned ? 'pin' : 'pin-filled'" 
            size="20" 
            color="#F97D1C"
          ></uni-icons>
          <text>{{ selectedRecord?.isPinned ? '取消置顶' : '置顶' }}</text>
        </view>
        <view class="menu-item danger" @click="handleDeleteRecord">
          <uni-icons type="trash" size="20" color="#EE3F4D"></uni-icons>
          <text>删除</text>
        </view>
        <view class="menu-cancel" @click="closeActionMenu">
          <text>取消</text>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue'
import { useCognitionStore } from '@/stores/cognitionStore'
import CapsuleNav from '@/components/common/CapsuleNav.vue'
import ThemeButton from '@/components/common/ThemeButton.vue'

const cognitionStore = useCognitionStore()
const actionMenu = ref(null)
const selectedRecord = ref(null)

// 初始化数据
onMounted(() => {
  cognitionStore.initFromStorage()
})

// 计算属性
const categories = computed(() => cognitionStore.categories)
const activeCategory = computed(() => cognitionStore.activeCategory)
const currentContents = computed(() => cognitionStore.currentContents)
const activeIndex = computed(() => 
  categories.value.findIndex(cat => cat === activeCategory.value)
)

// 日期格式化
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return `${date.getMonth()+1}/${date.getDate()} ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 生日格式化
const formatBirthday = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return `生日: ${date.getMonth()+1}月${date.getDate()}日`
}

// 分类操作
const handleCategoryChange = (index) => {
  cognitionStore.switchCategory(categories.value[index])
}

const handleAddCategory = () => {
  uni.showModal({
    title: '新建分类',
    content: '请输入分类名称',
    editable: true,
    success: ({ confirm, content }) => {
      if (confirm && content) {
        cognitionStore.addCategory(content.trim())
      }
    }
  })
}

const handleDeleteCategory = (name) => {
  if (['想法', '人际'].includes(name)) return
  
  uni.showModal({
    title: '删除分类',
    content: `确定删除分类"${name}"吗？`,
    success: ({ confirm }) => {
      if (confirm) {
        cognitionStore.deleteCategory(name)
      }
    }
  })
}

// 记录操作
const handleAddRecord = () => {
  const routeMap = {
    '人际': '/pages/cognition/contactEdit',
    '想法': '/pages/cognition/edit',
    '兴趣': '/pages/cognition/edit',
    '梦想': '/pages/cognition/edit'
  }
  const targetRoute = routeMap[activeCategory.value] || '/pages/cognition/edit'
  
  uni.navigateTo({
    url: targetRoute,
    success: () => {
      console.log('跳转成功:', targetRoute)
    },
    fail: (err) => {
      console.error('跳转失败:', err)
      uni.showToast({
        title: '无法打开编辑页面',
        icon: 'none'
      })
    }
  })
}

const handleEditRecord = (item) => {
  const routeMap = {
    '人际': '/pages/cognition/contactEdit',
    '想法': '/pages/cognition/edit',
    '兴趣': '/pages/cognition/edit',
    '梦想': '/pages/cognition/edit'
  }
  const targetRoute = routeMap[activeCategory.value] || '/pages/cognition/edit'
  
  uni.navigateTo({
    url: `${targetRoute}?id=${item.id}`,
    fail: (err) => {
      console.error('编辑跳转失败:', err)
      uni.showToast({
        title: '无法打开编辑页面',
        icon: 'none'
      })
    }
  })
}

const handleLongPress = (item) => {
  selectedRecord.value = item
  actionMenu.value?.open()
}

const handleTogglePin = async () => {
  if (selectedRecord.value) {
    await cognitionStore.togglePinContent(selectedRecord.value.id)
    closeActionMenu()
  }
}

const handleDeleteRecord = () => {
  if (!selectedRecord.value) return
  
  uni.showModal({
    title: '删除记录',
    content: `确定删除这条${activeCategory.value}记录吗？`,
    success: async ({ confirm }) => {
      if (confirm) {
        await cognitionStore.deleteContent(selectedRecord.value.id)
        closeActionMenu()
      }
    }
  })
}

const toggleReminder = async (id, enabled) => {
  await cognitionStore.updateContent(id, { reminderEnabled: enabled })
}

const closeActionMenu = () => {
  actionMenu.value?.close()
  selectedRecord.value = null
}
</script>

<style scoped>
.cognition-container {
  padding: 20rpx;
  position: relative;
  min-height: 100vh;
  background-color: #f5fbfe;
}

.waterfall-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
  margin-top: 20rpx;
}

.record-card {
  background-color: white;
  border-radius: 16rpx;
  padding: 20rpx; /* 减小内边距 */
  height: 192rpx; /* 原320rpx的3/5 */
  box-shadow: 0 2rpx 8rpx rgba(39, 117, 182, 0.1);
  border: 1rpx solid rgba(135, 206, 235, 0.3);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  overflow: hidden; /* 确保内容不溢出 */
}

.pinned-card {
  border-left: 6rpx solid #F97D1C;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.record-title {
  font-size: 28rpx; /* 适当减小字体 */
  color: #333;
  line-height: 1.3; /* 调整行高 */
  display: -webkit-box;
  -webkit-line-clamp: 1; /* 限制标题为1行 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  flex: 1;
}

.pin-icon {
  margin-left: 10rpx;
}

.record-desc {
  display: block;
  margin-top: 8rpx; /* 减小间距 */
  font-size: 24rpx;
  color: #666;
  -webkit-line-clamp: 1; /* 限制描述为1行 */
  display: -webkit-box;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.birthday-reminder {
  display: flex;
  align-items: center;
  margin-top: 8rpx;
}

.reminder-switch {
  transform: scale(0.7);
  transform-origin: left center;
}

.birthday-text {
  font-size: 24rpx;
  color: #666;
  margin-left: 6rpx;
  -webkit-line-clamp: 1;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.record-time {
  display: block;
  margin-top: 8rpx;
  font-size: 22rpx;
  color: #999;
}

.empty-tip {
  padding: 60rpx 40rpx;
  text-align: center;
  color: #999;
  font-size: 28rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.empty-tip uni-icons {
  margin-bottom: 20rpx;
}

.add-button {
  position: fixed;
  right: 32rpx;
  bottom: 120rpx;
  z-index: 100;
  width: 56px;
  height: 56px;
  border-radius: 50%;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-menu {
  background-color: white;
  border-radius: 16rpx 16rpx 0 0;
  padding-bottom: env(safe-area-inset-bottom);
}

.menu-item {
  padding: 24rpx;
  display: flex;
  align-items: center;
  border-bottom: 1rpx solid #eee;
}

.menu-item text {
  margin-left: 20rpx;
  font-size: 30rpx;
}

.menu-item.danger text {
  color: #EE3F4D;
}

.menu-cancel {
  padding: 24rpx;
  text-align: center;
  font-size: 30rpx;
  color: #333;
  margin-top: 8rpx;
  border-top: 1rpx solid #eee;
}
</style>